package com.derbysoft.synxisadapter.commons.repository.impl;

import com.derbysoft.synxisadapter.commons.model.Role;
import com.derbysoft.synxisadapter.commons.model.User;
import com.derbysoft.synxisadapter.commons.repository.UserRepository;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.Validate;
import org.hibernate.Hibernate;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public class UserRepositoryImpl extends BaseRepositorySupport implements UserRepository {
    @Override
    public User findByName(final String name) {
        Validate.notEmpty(name);
        User user = dataAccessor.load(User.class, name);
        Hibernate.initialize(user.getRoles());
        return user;
    }

    @Override
    public List<User> listAll() {
        return dataAccessor.findByClass(User.class, null, null);
    }

    @Transactional
    @Override
    public void saveRoles(String userName, String[] roleNames) {
        User user = findByName(userName);

        user.getRoles().clear();
        if (!ArrayUtils.isEmpty(roleNames)) {
            for (String roleName : roleNames) {
                Role role = dataAccessor.get(Role.class, roleName);
                if (role == null) {
                    throw new IllegalArgumentException("Can not found role with name:" + roleName);
                }
                user.getRoles().add(role);
            }
        }
        dataAccessor.save(user);
    }

    @Transactional
    @Override
    public void update(User user) {
        dataAccessor.saveOrUpdate(user);
    }

    @Transactional
    @Override
    public User create(String userName) {
        User user = new User();
        user.setName(userName);
        user.setDisabled(Boolean.FALSE);
        dataAccessor.save(user);
        return user;
    }

    @Transactional
    @Override
    public void disable(User user) {
        user.setDisabled(Boolean.TRUE);
        dataAccessor.save(user);
    }

    @Transactional
    @Override
    public void enable(User user) {
        user.setDisabled(Boolean.FALSE);
        dataAccessor.save(user);
    }
}